package leetcode.code1717;

import java.util.Stack;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int maximumGain(String s, int x, int y) {
		char[] cs = s.toCharArray();
		if (x >= y) {
			return this.maximumGain(cs, x, y, 'a', 'b');
		}
		return this.maximumGain(cs, y, x, 'b', 'a');
	}

	private int maximumGain(char[] cs, int max, int min, char s, char p) {
		Stack<Character> stack = new Stack<>();
		int ans = 0;
		for (int i = 0; i <= cs.length; i++) {
			char c = i < cs.length ? cs[i] : 0;
			if ((c != 'a' && c != 'b') || c == 0) {
				ans += this.maximumGain(stack, min, s, p);
			} else {
				if (c == p && !stack.isEmpty() && stack.peek() == s) {
					ans += max;
					stack.pop();
				} else {
					stack.add(c);
				}
			}
		}
		return ans;
	}

	private int maximumGain(Stack<Character> stack, int min, char s, char p) {
		int ans = 0;
		Stack<Character> tmp = new Stack<>();
		while (!stack.isEmpty()) {
			char c = stack.pop();
			if (c == p && !tmp.isEmpty() && tmp.peek() == s) {
				ans += min;
				tmp.pop();
			} else {
				tmp.add(c);
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(11, this.maximumGain("aabbab", 3, 5));
		H.compare(20, this.maximumGain("aabbaaxybbaabb", 5, 4));
		H.compare(19, this.maximumGain("cdbcbbaaabab", 4, 5));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
